<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>侦听器</title>
        <style type="text/css">
            .wrapper { display: flex ; }
            .wrapper>span { 
                flex-basis: 100px ; 
                border: 1px solid #dedede;
                text-align: center ;
            }
        </style>
        <script src="https://unpkg.com/vue@next"></script>
    </head>
    <body>

        <h3>侦听器(watcher)</h3>

        <div id="watch-object">
            <input v-model="course.id" placeholder="course id">
            <input v-model="course.name" placeholder="course name">
            <input v-model="course.credit" placeholder="course credit">
            <input v-model="course.teacher.id" placeholder="teacher id">
            <input v-model="course.teacher.name" placeholder="teacher name">
            <hr>
            <div class="wrapper">
                <span>{{ course.id }}</span>
                <span>{{ course.name }}</span>
                <span>{{ course.credit }}</span>
                <span>{{ course.teacher.id }}</span>
                <span>{{ course.teacher.name }}</span>
            </div>
        </div>

        <script type="text/javascript">
            const app = Vue.createApp({
                // 为根组件指定 Data Property
                data(){
                    return {
                        course: {
                            id: 1001 ,
                            name: 'JavaScript' ,
                            credit: 2 ,
                            teacher: {
                                id: 1 ,
                                name: '相爷' 
                            }
                        }
                    }
                },
                // 为根组件指定侦听器(watcher)
                watch: {
                   course: {
                       // 注意: 参数 value 和 old 都表示对象而不是属性
                       handler( value , old ) {
                           console.log( "侦听到course内部的变化" );
                           if( value.name != 'JavaScript' ) {
                               console.log( '修改name属性' );
                           }
                       },
                       // 不论对象的属性层级有多深，只要 deep 为 true 就都可以被 侦听
                       deep: true
                   }
                }
            });
            const vm = app.mount( '#watch-object' );
            console.log( vm );
        </script>
        
    </body>
</html>